﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Data.Common;

namespace SmartLib.Dal.Sql
{
    public class Query<T>
    {
        private QueryExpressionVistor _vistor;

        internal Query(Expression<Func<T, bool>> predicate)
        {
            _vistor = new QueryExpressionVistor(predicate);
        }

        /// <summary>
        /// 创建带Lamber表达式的Query查询条件
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public static Query<T> Conditions(Expression<Func<T, bool>> predicate)
        {
            return new Query<T>(predicate);
        }

        /// <summary>
        /// 生成查询条件文本，并附加DbCommand参数
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public string BuildSql(DbCommand cmd)
        {
            return _vistor.BuildSql(cmd);
        }

        /// <summary>
        /// 生成查询条件文本，并附加DbCommand参数
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="prefix"></param>
        /// <returns></returns>
        public string BuildSqlWithPrefix(DbCommand cmd, string prefix)
        {
            return _vistor.BuildSqlWithPrefix(cmd, prefix);
        }

        /// <summary>
        /// 生成查询条件文本，并附加DbCommand参数
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="parameterToken"></param>
        /// <returns></returns>
        public string BuildSql(DbCommand cmd, string parameterToken)
        {
            return _vistor.BuildSql(cmd, parameterToken);
        }

        public string BuildSqlWithPrefix(DbCommand cmd, string parameterToken, string prefix)
        {
            return _vistor.BuildSqlWithPrefix(cmd, parameterToken, prefix);
        }

        /// <summary>
        /// 生成查询条件文本，并附加DbCommand参数
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="buildParameter"></param>
        /// <returns></returns>
        public string BuildSql(DbCommand cmd, Func<string, string> buildParameter)
        {
            return _vistor.BuildSql(cmd, buildParameter);
        }

        /// <summary>
        /// 生成查询条件文本，并附加DbCommand参数
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="buildParameter"></param>
        /// <param name="prefix"></param>
        /// <returns></returns>
        public string BuildSqlWithPrefix(DbCommand cmd, Func<string, string> buildParameter, string prefix)
        {
            return _vistor.BuildSqlWithPrefix(cmd, buildParameter, prefix);
        }
    }
}
